

import { ref, unref } from 'vue';
import { tryOnUnmounted } from '@vueuse/core';

export function useCountdown(count: number) {
    // 用来记录当前的数字	
    const currentCount = ref(count);

    // 用来记录是否开始计时了	
    const isStart = ref(false);

    // 记录定时器	
    let timerId: ReturnType<typeof setInterval> | null;

    // 清除定时器	
    function clear() {
        timerId && window.clearInterval(timerId);
    }

    // 停止计时	
    function stop() {
        isStart.value = false;
        clear();
        timerId = null;
    }

    //重置	
    function reset() {
        currentCount.value = count;
        stop();
    }

    // 开始计时	
    function start() {
        if (unref(isStart) || !!timerId) {
            return;
        }
        isStart.value = true;
        timerId = setInterval(() => {
            if (unref(currentCount) === 1) {
                // 计时结束，恢复初始	
                reset();
            } else {
                // 计时继续，每次减一	
                currentCount.value -= 1;
            }
        }, 1000);
    }

    // 重启
    function restart() {
        reset();
        start();
    }

    // 组件销毁的时候记得初始化	
    tryOnUnmounted(() => {
        reset();
    });

    return { start, reset, restart, clear, stop, currentCount, isStart };
}